package la.renzhen.rtpt.admin.source.redis;

import com.alibaba.fastjson.JSON;
import la.renzhen.rtpt.admin.source.CenterConfigurationSource;
import la.renzhen.rtpt.admin.source.ConfigElement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * @author <a href="mailto:zhouhaichao@2008.sina.com">haiker</a>
 * @version 11/05/2018 4:43 PM
 */
@Slf4j
public class RedisCenterConfigurationSource implements CenterConfigurationSource {

    Jedis jedis;
    String module;

    public RedisCenterConfigurationSource(Jedis jedis, String module) {
        this.jedis = jedis;
        this.module = module;
    }

    @Override
    public List<String> environments() {
        return jedis.hgetAll(module + ":env")
                .entrySet().stream()
                .filter(s -> Integer.parseInt(s.getValue()) > 0)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

    @Override
    public List<ConfigElement> loadAll(String environment, String prefix) {
        return jedis.keys(key(environment, prefix).append("*").toString())
                .stream()
                .map(s -> JSON.parseObject(jedis.get(s), ConfigElement.class))
                .collect(Collectors.toList());
    }

    @Override
    public ConfigElement get(String environment, String key) {
        return null;
    }

    @Override
    public void set(ConfigElement item) {
        jedis.hincrBy(envKey(), item.getEnvironment(), 1);
        jedis.set(key(item.getEnvironment(), item.getKey()).toString(), JSON.toJSONString(item));
    }

    @Override
    public void del(String environment, String key) {
        jedis.hincrBy(envKey(), environment, -1);
        String rk = key(environment, key).toString();
        long n = jedis.del(rk);
        log.info("del key {} = {}", rk, n);
    }

    protected StringBuilder key(String environment, String key) {
        StringBuilder keys = new StringBuilder(module);
        keys.append(":");
        keys.append(environment).append(":");
        if (StringUtils.hasText(key)) {
            keys.append(key);
        }
        return keys;
    }

    protected String envKey() {
        return module + ":env";
    }
}
